package com.hg.hggood.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.hg.hggood.common.AlipayProperties;
import com.hg.hggood.entity.Order;
import com.hg.hggood.entity.OrderItem;
import com.hg.hggood.mapper.OrderMapper;
import com.hg.hggood.service.IAlipayService;
import com.hg.hggood.service.ex.AccessDeniedException;
import com.hg.hggood.service.ex.InsertException;
import com.hg.hggood.service.ex.OrderNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AlipayServiceImpl implements IAlipayService {
    @Autowired AlipayProperties alipayProperties;
    @Autowired AlipayClient alipayClient;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public AlipayTradePagePayRequest payPage(Integer oid,Integer uid, String username) throws AlipayApiException {
        Order result = orderMapper.findByOid(oid);
        if (result == null){
            throw new OrderNotFoundException("该订单序号不存在的异常");
        }
        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据访问");
        }
        AlipayTradePagePayModel model=new AlipayTradePagePayModel();
//        Random random = new Random();
//        Integer i = random.nextInt(1000000000);
//        model.setOutTradeNo(i.toString());       //商户订单号(订单号是唯一的，所以推荐使用不会与下一次重复的字符串)
        model.setOutTradeNo(result.getOnum());
        model.setProductCode("FAST_INSTANT_TRADE_PAY");  //电脑网站支付销售产品码，不同的支付方式productCode不同
        model.setSubject("hggood测试");         //订单标题
        model.setTotalAmount("0.02");        //订单总金额
        model.setTimeoutExpress("1m");     //支付超市时间，1h后关闭

        AlipayTradePagePayRequest request=new AlipayTradePagePayRequest();
        request.setBizModel(model);
        request.setReturnUrl(alipayProperties.getReturnUrl());   //支付成功后同步返回的url地址
        request.setNotifyUrl(alipayProperties.getNotifyUrl());   //trade_success、trade_closed触发
        return request;
    }

    @Override
    public AlipayTradeWapPayRequest payWap(Integer oid, Integer uid, String username) throws AlipayApiException {
        Order result = orderMapper.findByOid(oid);
        if (result == null){
            throw new OrderNotFoundException("该订单序号不存在的异常");
        }
        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据访问");
        }
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(result.getOnum());
        model.setProductCode("QUICK_WAP_WAY");
//        model.setSubject("测试");         //订单标题
        List<OrderItem> list = orderMapper.findItemByOid(oid);
        String title = "";
        for (OrderItem d :list){
            title += d.getTitle();
        }
        model.setSubject(title);
//        model.setTotalAmount("0.01");        //订单总金额
        model.setTotalAmount(result.getTotalPrice().toString());
        model.setTimeoutExpress("1h");     //支付超市时间，1h后关闭
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setBizModel(model);
        request.setReturnUrl(alipayProperties.getReturnUrl());   //支付成功后同步返回的url地址
        request.setNotifyUrl(alipayProperties.getNotifyUrl());   //trade_success、trade_closed触发
        return request;
    }

    @Override
    public AlipayTradeQueryResponse Query(Integer oid, Integer uid, String username) throws Exception {
        Order result = orderMapper.findByOid(oid);
        if (result == null){
            throw new OrderNotFoundException("该订单序号不存在的异常");
        }
        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据访问");
        }
        AlipayTradeQueryModel model=new AlipayTradeQueryModel();
        model.setOutTradeNo(result.getOnum());

        AlipayTradeQueryRequest request=new AlipayTradeQueryRequest();
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        //getCode()  40004交易不存在  10000交易成功
        if ("10000".equals(response.getCode())){
            Integer rows = orderMapper.updateStatusByOid(
                    oid,1,response.getSendPayDate(),username,new Date());
            if (rows != 1){
                throw new InsertException("插入数据异常");
            }
        }
//        System.out.println(response.getCode()+"%%%%");
        return response;
    }
}
